package com.example.springboot.service.admin.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.springboot.config.Shiro.security.SecurityUtil;
import com.example.springboot.mapper.CmsUserMapper;
import com.example.springboot.mapper.SuggesMapper;
import com.example.springboot.model.entity.CmsUser;
import com.example.springboot.model.entity.Sugges;
import com.example.springboot.model.form.Result;
import com.example.springboot.model.req.admin.SuggesReq;
import com.example.springboot.model.sys.SysUser;
import com.example.springboot.model.vo.SuggesVO;
import com.example.springboot.service.admin.SuggesService;
import com.example.springboot.utils.CopyUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

/**
 * @author zf
 * @意见建议表
 * @since 2021-06-04
 */
@Service
public class SuggesServiceImpl extends ServiceImpl<SuggesMapper, Sugges> implements SuggesService {

    @Resource
    CmsUserMapper cmsUserMapper;

    @Override
    public Result getPage(SuggesReq req) {
        List<Sugges> SuggesList = list(new LambdaQueryWrapper<Sugges>()
                .eq(Sugges::getInvalid, 0)
                .orderByDesc(Sugges::getCreateTime)
                .last("limit 5"));

        return Result.buildSuccess(SuggesList.stream().map(e -> {
            SuggesVO vo = CopyUtil.copyObject(e, SuggesVO.class);
            if (Objects.nonNull(e.getUserId())) {
                CmsUser cmsUser = cmsUserMapper.selectById(e.getUserId());
                vo.setUserName(cmsUser.getRealname());
            }
            return vo;
        }));
    }

    @Override
    public Result addInfo(SuggesReq req) {
        //主表复制元素
        Sugges sugges = CopyUtil.copyObject(req, Sugges.class);
        boolean flag;
        if (req.getId() != null) {
            flag = updateById(sugges);
        } else {
            SysUser sysUser = SecurityUtil.sysUser();
            if (Objects.nonNull(sysUser)) {
                sugges.setUserId(sysUser.getId());
            }
            flag = save(sugges);
        }
        if (flag) {
            return Result.buildSuccess();
        }
        return Result.buildFail();
    }

    @Override
    public Result deleteInfos(String ids) {
        if (update(new UpdateWrapper<Sugges>().lambda()
                .set(Sugges::getInvalid, 1)
                .inSql(Sugges::getId, ids)
        )) {
            return Result.buildSuccess();
        }
        return Result.buildFail();
    }

}
